package com.nulldev.util.net.dsap.demo;

import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.lang.json.JsonObject;
import com.nulldev.util.net.IPUtil;
import com.nulldev.util.net.dsap.DSAPAllocation;
import com.nulldev.util.net.packets.NetInfoAdapter;
import com.nulldev.util.net.packets.NetPacket;
import com.nulldev.util.net.packets.PacketManager;
import com.nulldev.util.net.packets.PacketMode;
import com.nulldev.util.net.tcp.TCPCore;
import com.nulldev.util.net.tcp.client.TCPClient;
import com.nulldev.util.net.tcp.server.TCPServer;

public class DSAPDemo {

	public static void main(String[] args) {
		final int port = IPUtil.nextFreePort();
		final TCPServer s = new TCPServer("DSAP Demo", "dsap.demo", port) {
			
			@Override
			public void receive(TCPCore connection, String event, String payload, byte[] bytes, long length, final long readTime) {
				final NetPacket packet = PacketManager.parsePacket(this, null, event, bytes);
				if (!packet.isGeneric()) {
					packet.server(packet.getData(), event, NetInfoAdapter.create(connection));
				}
			}
		};
		s.start();
		final TCPClient tcpc = new TCPClient("DSAP Demo Client", "dsap.demo.client", "127.0.0.1", port) {
			
			@Override
			public void receive(String event, String payload, byte[] bytes, long count, final long readTime) {
				final NetPacket packet = PacketManager.parsePacket(this, null, event, bytes);
				if (!packet.isGeneric()) {
					packet.client(packet.getData(), event, NetInfoAdapter.create(this.getConnection()));
				}
			}

			@Override
			public void onDSAP(JsonObject obj) {
				final DSAPAllocation alloc = new DSAPAllocation(obj);
				alloc.create();
				alloc.sendBlocking(PacketManager.fromID("ERRORED", "S Hello to you via DSAP!"), 
						PacketMode.STANDARD_V2_FULLY_ENCRYPTED, alloc.attemptNetInfo());
				alloc.stop();
			}
		};
		tcpc.start();
		tcpc.sendBlocking(PacketManager.fromID("dsap.check", ""));
		tcpc.sendBlocking(PacketManager.fromID("dsap.check.encryption", ""));
		tcpc.sendBlocking(PacketManager.fromID("dsap.request", "1"));
	}

}
